<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/roles' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图 -->
    <el-card>
      <el-button type="primary" @click="dialogVisible = true">添加角色</el-button>
      <template>
        <el-table :data="rolesList" style="width: 100%" stripe border>
          <!-- 展开列 -->
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row
                :class="['bdbottom','vcenter']"
                v-for="item1 in scope.row.children"
                :key="item1.id"
              >
                <!-- 一级菜单 -->
                <el-col :span="5">
                  <el-tag closable @close="removeTag(scope.row,item1.id)">{{item1.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 二级菜单 -->
                <el-col :span="19">
                  <!-- 通过<el-row></el-row> -->
                  <el-row
                    :class="['bddtop','vcenter']"
                    v-for="item2 in item1.children"
                    :key="item2.id"
                  >
                    <el-col :span="6">
                      <el-tag
                        closable
                        @close="removeTag(scope.row,item2.id)"
                        type="success"
                      >{{item2.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="18">
                      <el-tag
                        closable
                        @close="removeTag(scope.row,item3.id)"
                        v-for="item3 in item2.children"
                        :key="item3.id"
                        type="warning"
                      >{{item3.authName}}</el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <!-- 索引列 -->
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column prop="roleName" label="角色名称" width="300"></el-table-column>
          <el-table-column prop="roleDesc" label="角色描述" width="300"></el-table-column>
          <el-table-column prop="level" label="操作">
            <!-- 自定义权限等级，所以使用作用域插槽：获取数据 -->
            <template slot-scope="scope">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="rolesModifyDialogVisible(scope.row.id)"
              >编辑</el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="rolesDeleteDialogVisible(scope.row.id)"
              >删除</el-button>
              <el-tooltip
                class="item"
                effect="dark"
                content="分配角色"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="warning"
                  icon="el-icon-setting"
                  size="mini"
                  @click="rightAvarage(scope.row)"
                >分配权限</el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-card>
    <!-- 添加角色的弹框 -->
    <el-dialog title="提示" :visible.sync="dialogVisible" width="50%" @close="roleDialogClose">
      <!-- 添加用户的主体区 -->
      <el-form :model="roleForm" :rules="roleFormRules" ref="roleFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="rolesAdd">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色的弹框 -->
    <el-dialog
      title="编辑角色信息"
      :visible.sync="editDialogChange"
      width="50%"
      @close="roleModifyDialogClose"
    >
      <!-- 添加用户的主体区 -->
      <el-form
        :model="modifyRoles"
        :rules="roleFormRules"
        ref="roleModifyFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="modifyRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="modifyRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogChange = false">取 消</el-button>
        <el-button type="primary" @click="rolesModify">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 权限数据 -->
    <el-dialog title="分配权限" :visible.sync="setRightsDialogVisible" width="50%">
      <el-tree
        :data="rightAvarageData"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defkeys"
        @close="setNull"
        ref="RightRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      rolesList: [],
      //   添加用户的弹框判断,刚开始是隐藏的，为false，只有点击之后，才为true
      dialogVisible: false,
      //   编辑
      editDialogChange: false,
      // 权限弹框
      setRightsDialogVisible: false,
      // 权限数据
      rightAvarageData: [],
      // 添加角色的信息数据
      roleForm: {
        roleName: "",
        roleDesc: ""
      },

      // 验证角色信息
      roleFormRules: {
        roleName: [
          {
            required: true,
            message: "请输入角色名称",
            trigger: "blur"
          },
          {
            min: 2,
            max: 20,
            message: "角色名称长度在2-20个字符之间",
            trigger: "blur"
          }
        ],
        roleDesc: [
          {
            required: true,
            message: "请输入角色描述",
            trigger: "blur"
          },
          {
            min: 2,
            max: 20,
            message: "角色描述长度在2-20个字符之间",
            trigger: "blur"
          }
        ]
      },
      //   查询到的数据存在modifyRoles
      modifyRoles: {},
      // 属性控件的属性绑定对象
      treeProps: {
        // 看到的是哪个属性对应的值
        label: "authName",
        // 父子节点通过哪个属性实现嵌套
        children: "children"
      },
      // 默认选中的节点id值
      defkeys: [],
      // 即将分配权限的id
      roleId:''
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    // 删除权限
    async removeTag(role, rightId) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (confirmResult !== "confirm")
        return this.$message.info("取消删除角色管理");
      // 已近能删除，调用删除的接口请求
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      if (res.meta.status !== 200) return this.$message.error("删除失败");
      // 刷新数据
      // 会发生页面的完整渲染
      // this.getRolesList();
      // 把服务器返回的最新权限，直接复制给children，能防止列表的全部刷新
      role.children = res.data;
      // 信息提示
      this.$message.success("已经删除");
    },
    //   获取角色列表信息
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      //   console.log(res);
      if (res.meta.status !== 200) return this.$meaasge.error("获取角色列失败");
      this.rolesList = res.data;
      this.$message.success("获取角色列表成功");
    },
    // 获取添加用户的数据
    // 1：点击取消，清空表单数据
    roleDialogClose() {
      this.$refs.roleFormRef.resetFields();
    },
    roleModifyDialogClose() {
      this.$refs.roleModifyFormRef.resetFields();
    },
    // 2:调用接口，请求添加角色列表
    rolesAdd() {
      // 在发送请求前，先进行预校验
      this.$refs.roleFormRef.validate(async valid => {
        console.log(valid);
        if (!valid) return this.$message.error("请输入合法角色名称");
        // 请求接口
        const { data: res } = await this.$http.post("roles", this.roleForm);
        console.log(res);
        this.dialogVisible = false;
        this.$message.success("添加角色成功");
      });
    },
    // 根据id查询角色列表
    async rolesModifyDialogVisible(id) {
      this.editDialogChange = true;
      const { data: res } = await this.$http.get("roles/" + id);
      console.log(res);

      if (res.meta.status !== 200)
        return this.$message.error("查询角色列表失败");
      this.modifyRoles = res.data;
      this.$message.success("查询角色列表成功");
    },
    rolesModify() {
      // 确认修改之前，先做校验
      this.$refs.roleModifyFormRef.validate(async valid => {
        if (!valid) return this.$message.error("请是输入正确的数据");
        //   校验通过，调用修改接口
        const { data: res } = await this.$http.put(
          "roles/" + this.modifyRoles.roleId,
          {
            roleName: this.modifyRoles.roleName,
            roleDesc: this.modifyRoles.roleDesc
          }
        );
        console.log(res);
        if (res.meta.status !== 200)
          return this.$message.error("角色信息未修改成功");
        this.editDialogChange = false;
        this.getRolesList();
        // this.$message.success("角色信息修改成功");
      });
    },
    // 根据id删除角色
    async rolesDeleteDialogVisible(id) {
      console.log(id);

      // 询问用户是否要删除
      // 否：提示未删除，退出
      // 是，调用接口删除，更新数据
      const deleteConfirm = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (deleteConfirm !== "confirm")
        return this.$message.info("已经取消删除");
      //   console.log("删除成功");
      const { data: res } = await this.$http.delete("roles/" + id);
      //   console.log(res);
      if (res.meta.status !== 200) return this.$message.error("删除用户失败");
      // 刷新数据
      this.getRolesList();

      //    提示
      this.$message.success("已经删除成功");
    },
    // 权限分配
    async rightAvarage(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get("rights/tree");
      console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error("获取权限列表失败");
      this.rightAvarageData = res.data;
      this.getLeafKeys(role, this.defkeys);
      this.setRightsDialogVisible = true;
      this.$message.success("获取权限列表成功");
    },
    // 递归函数,获取角色下所有三级权限的id，并保存在数组中
    getLeafKeys(node, arr) {
      // 当前node节点不包含children属性，就是三级节点
      if (!node.children) {
        return app.pudh(node.id);
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr);
      });
    },
    // 监听分配权限对话框的关闭事件
    setNull() {
      this.defkeys = [];
    },
    // 获取角色分配选中的id
   async allRight() {
      const keys = [
        ...this.$refs.RightRef.getCheckedKeys(),
        ...this.$refs.RightRef.getHalfCheckedKeys()
      ];
      console.log(keys);
      const idStr = keys.join(',')
      console.log('123');
      
      const {data: res} =  await this.$http.post( `roles/${this.roleId}/rights`,{ rids: idStr })
      console.log(res);
      
      if (res.meta.status !==200 ) return this.$message.error('分配权限失败')
      this.$message.success('分配权限成功')
      this.getRolesList();
      this.setRightsDialogVisible = false
    }
  }
};
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>